"""
RagFlow 客户端 GUI 上传文件选项卡组件
"""

import os
from PySide6.QtCore import Qt, Signal
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QLabel, QLineEdit, QPushButton, QFileDialog,
    QListWidget, QMessageBox, QProgressDialog, QSpinBox
)

from ragflow_client.config import RagFlowConfig
from ragflow_client.utils.file_util import get_files
from ragflow_client.gui.components.threads import UploadFilesThread


class UploadTabWidget(QWidget):
    """上传文件选项卡组件"""
    
    # 定义信号
    log_message = Signal(str)
    upload_result = Signal(int, int)
    
    def __init__(self, parent=None):
        """初始化上传文件选项卡组件"""
        super().__init__(parent)
        self.parent = parent
        self.current_thread = None
        self.setup_ui()
    
    def setup_ui(self):
        """创建界面"""
        # 创建布局
        layout = QGridLayout(self)
        
        # 文档目录
        layout.addWidget(QLabel("文档目录:"), 0, 0)
        
        dir_layout = QHBoxLayout()
        layout.addLayout(dir_layout, 0, 1)
        
        self.doc_dir_edit = QLineEdit()
        dir_layout.addWidget(self.doc_dir_edit)
        
        browse_button = QPushButton("浏览...")
        browse_button.clicked.connect(self.browse_directory)
        dir_layout.addWidget(browse_button)
        
        # 文档后缀
        layout.addWidget(QLabel("文档后缀:"), 1, 0)
        self.doc_suffix_edit = QLineEdit()
        layout.addWidget(self.doc_suffix_edit, 1, 1)
        
        # 批次大小
        layout.addWidget(QLabel("批次大小:"), 2, 0)
        self.batch_size_spin = QSpinBox()
        self.batch_size_spin.setRange(1, 100)
        self.batch_size_spin.setValue(10)
        layout.addWidget(self.batch_size_spin, 2, 1, alignment=Qt.AlignLeft)
        
        # 文件列表
        layout.addWidget(QLabel("文件列表:"), 3, 0)
        
        # 创建文件列表
        self.files_list = QListWidget()
        layout.addWidget(self.files_list, 4, 0, 1, 2)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        layout.addLayout(button_layout, 5, 0, 1, 2)
        
        # 刷新文件列表按钮
        refresh_button = QPushButton("刷新文件列表")
        refresh_button.clicked.connect(self.refresh_file_list)
        button_layout.addWidget(refresh_button)
        
        # 上传文件按钮
        upload_button = QPushButton("上传文件")
        upload_button.clicked.connect(self.upload_files)
        button_layout.addWidget(upload_button)
        
        # 添加弹性空间
        button_layout.addStretch()
    
    def browse_directory(self) -> None:
        """浏览文件夹"""
        directory = QFileDialog.getExistingDirectory(self, "选择文档目录")
        if directory:
            self.doc_dir_edit.setText(directory)
            self.refresh_file_list()
    
    def refresh_file_list(self) -> None:
        """刷新文件列表"""
        # 获取文档目录
        doc_dir = self.doc_dir_edit.text().strip()
        if not doc_dir:
            QMessageBox.critical(self, "错误", "请先选择文档目录")
            return
        
        # 获取文档后缀
        doc_suffix_str = self.doc_suffix_edit.text().strip()
        if not doc_suffix_str:
            QMessageBox.critical(self, "错误", "请先设置文档后缀")
            return
        
        doc_suffix = [s.strip() for s in doc_suffix_str.split(",") if s.strip()]
        
        # 获取文件列表
        try:
            files = get_files(doc_dir, doc_suffix)
            
            # 清空列表框
            self.files_list.clear()
            
            # 添加文件到列表框
            for file in files:
                # 显示相对路径
                rel_path = os.path.relpath(file, doc_dir)
                self.files_list.addItem(rel_path)
            
            # 显示文件数量
            QMessageBox.information(self, "文件列表", f"找到 {len(files)} 个文件")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"获取文件列表失败: {str(e)}")
    
    def upload_files(self) -> None:
        """上传文件"""
        # 获取主窗口中的配置
        if not hasattr(self.parent, "get_current_config"):
            QMessageBox.critical(self, "错误", "无法获取配置信息")
            return
        
        config = self.parent.get_current_config()
        
        # 从界面获取文档目录和后缀
        doc_dir = self.doc_dir_edit.text().strip()
        doc_suffix_str = self.doc_suffix_edit.text().strip()
        batch_size = self.batch_size_spin.value()
        
        # 验证必填字段
        if not config.api_url:
            QMessageBox.critical(self, "错误", "API 地址不能为空")
            return
        
        if not config.api_key:
            QMessageBox.critical(self, "错误", "API 密钥不能为空")
            return
        
        if not config.kb_id:
            QMessageBox.critical(self, "错误", "知识库 ID 不能为空")
            return
        
        if not doc_dir:
            QMessageBox.critical(self, "错误", "文档目录不能为空")
            return
        
        if not doc_suffix_str:
            QMessageBox.critical(self, "错误", "文档后缀不能为空")
            return
        
        # 解析文档后缀
        doc_suffix = [s.strip() for s in doc_suffix_str.split(",") if s.strip()]
        
        # 创建临时配置
        upload_config = RagFlowConfig(
            api_url=config.api_url,
            api_key=config.api_key,
            kb_id=config.kb_id,
            kb_name=config.kb_name,
            parser_id=config.parser_id,
            doc_dir=doc_dir,
            doc_suffix=doc_suffix,
            debug=config.debug
        )
        
        # 创建进度对话框
        progress = QProgressDialog("正在上传文件...", "取消", 0, 100, self)
        progress.setWindowTitle("上传文件")
        progress.setWindowModality(Qt.WindowModal)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.show()
        
        # 创建并启动工作线程
        self.current_thread = UploadFilesThread(upload_config, batch_size)
        self.current_thread.finished.connect(lambda status, msg: self.handle_upload_finished(status, msg, progress))
        self.current_thread.progress.connect(progress.setValue)
        self.current_thread.status_update.connect(lambda msg: self.log_message.emit(msg))
        self.current_thread.upload_result.connect(self.handle_upload_result)
        progress.canceled.connect(self.current_thread.cancel)
        self.current_thread.start()
    
    def handle_upload_finished(self, status: bool, msg: str, progress: QProgressDialog) -> None:
        """
        处理上传完成事件
        
        Args:
            status: 上传状态
            msg: 消息
            progress: 进度对话框
        """
        # 关闭进度对话框
        progress.close()
        
        # 如果没有成功，显示错误消息
        if not status:
            QMessageBox.critical(self, "错误", f"上传失败: {msg}")
        
        # 清理线程
        self.current_thread = None
    
    def handle_upload_result(self, success_count: int, failed_count: int) -> None:
        """
        处理上传结果
        
        Args:
            success_count: 成功数量
            failed_count: 失败数量
        """
        if failed_count == 0:
            QMessageBox.information(self, "成功", f"所有文件上传成功，共 {success_count} 个文件")
        else:
            QMessageBox.warning(self, "警告", f"部分文件上传失败，成功: {success_count}，失败: {failed_count}")
        
        # 发送上传结果信号
        self.upload_result.emit(success_count, failed_count)